package com.wuseguang.springcloud.util;

public class byteUtil {

    public static int toInt(byte[] bytes){
        int number = 0;
        for(int i = 0; i < 4 ; i++){
            number += bytes[i] << i*8;
        }
        return number;
    }

    /**
     * 获取byte的实际长度
     * @param bytes
     * @return
     */
    public  static int getValidLength(byte[] bytes){
        int i = 0;
        if (null == bytes || 0 == bytes.length)
            return i ;
        for (; i < bytes.length; i++) {
            if (bytes[i] == '\0')
                break;
        }
        return i + 1;
    }

    /**
     * mac地址转为6字节
     */
    public static byte[] getMacBytes(String mac) {
        byte[] macBytes = new byte[6];
        String[] strArr = mac.split(":");
        for (int i = 0; i < strArr.length; i++) {
            int value = Integer.parseInt(strArr[i], 16);
            macBytes[i] = (byte) value;
        }
        return macBytes;
    }

    /**
     * 将Mac地址的数组形式转换为字符串形式
     * @param macBytes mac地址的数组形式
     * @return Mac地址的字符串，格式如：78:44:fd:c9:87:a0
     */
    public static String getMacString(byte[] macBytes) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < macBytes.length; i++) {

            String s =Integer.toHexString(0xFF & macBytes[i]);
            //如果长度等于0
            if(s.length()==1){
                s="0"+s;
            }

            builder.append(':').append(s);
        }
        return builder.substring(1);
    }

}
